/**
 * LoginDialog.java
 */

 /**
 *  AdSec: Administrador de Secundarias
 *  Copyright (C) 2009 Daniela Ramírez Chaves (dannyrch@gmail.com)
 *  Copyright (C) 2009 Leonel Salazar Valverde (leo87sv@gmail.com)
 *
 *  This file is part of AdSec.
 *  AdSec is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AdSec is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AdSec.  If not, see <http://www.gnu.org/licenses/>.
 */

package adsec.presentacion;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Connection;
import java.sql.Date;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;
import adsec.datos.AdministradorConexion;
import adsec.negocios.ControladoraLogin;
import adsec.negocios.ControladoraUsuario;
import adsec.negocios.UtilidadesCapaNegocios;
import org.jdesktop.application.Action;


public class LoginDialog extends javax.swing.JDialog implements KeyListener{

    private Dimension tamañoPanelGrande = new Dimension(405, 470);
    private Dimension tamañoPanelPequeño = new Dimension(405, 270);
    private ControladoraLogin controladoraLogin;

    /** Creates new form LoginDialog */
    public LoginDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.controladoraLogin = new ControladoraLogin();
        this.controladoraLogin.leerDatosConfiguracion();
        this.txtUsuario.setText(this.controladoraLogin.getUsuario());
        this.txtPassword.setText(this.controladoraLogin.getPassword());
        String tmp = this.controladoraLogin.getServidorBD();
        if(tmp != null){
            this.txtDirServidor.setText(tmp);
        }
        tmp = this.controladoraLogin.getPuerto();
        if(tmp != null){
            this.txtPuerto.setText(tmp);
        }
        tmp = this.controladoraLogin.getUsuarioBD();
        if(tmp != null){
            this.txtUsuarioBD.setText(tmp);
        }
        tmp = this.controladoraLogin.getPasswordBD();
        if(tmp != null){
            this.txtPasswordBD.setText(tmp);
        }
		tmp = this.controladoraLogin.getNombreBD();
		if(tmp != null){
			this.txtNombreBD.setText(tmp);
		}
        this.chbGuardarPassword.setSelected(this.controladoraLogin.isGuardarPasswd());
        this.setModalityType(ModalityType.APPLICATION_MODAL);
        try{
            Dimension tamañoPantalla = Toolkit.getDefaultToolkit().getScreenSize();
            this.setBounds( (int)(tamañoPantalla.getWidth() - this.tamañoPanelPequeño.getWidth())/2 ,
                    (int)(tamañoPantalla.getHeight() - this.tamañoPanelPequeño.getHeight())/2 ,
                    0,0);
        }catch(Exception e){
            System.err.println(e.getMessage());
        }
        this.switchAvanzado();
        this.txtUsuario.addKeyListener(this);
        this.txtPassword.addKeyListener(this);
        this.btnIngresar.addKeyListener(this);
        this.txtPassword.requestFocusInWindow();
    }//fin de constructor

    protected MaskFormatter createFormatter(String s) {
        MaskFormatter formatter = null;
        try {
            formatter = new MaskFormatter(s);
        } catch (java.text.ParseException exc) {
            System.err.println("formatter is bad: " + exc.getMessage());
            System.exit(-1);
        }
        return formatter;
    }

    public void keyTyped(KeyEvent evento){

    }

    public void keyPressed(KeyEvent evento){
        if( evento.getKeyCode() == KeyEvent.VK_ENTER){
            this.accionIngresar();
        }
    }

    public void keyReleased(KeyEvent evento){
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbFotoLiceo = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtFechaHora = new javax.swing.JTextField();
        btnAvanzado = new javax.swing.JToggleButton();
        btnIngresar = new javax.swing.JButton();
        lbUsuario = new javax.swing.JLabel();
        lbPassword = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        txtPassword = new javax.swing.JPasswordField();
        btnCancelar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtDirServidor = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtUsuarioBD = new javax.swing.JTextField();
        txtPasswordBD = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        chbGuardarPassword = new javax.swing.JCheckBox();
        btnProbarConexion = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        txtPuerto = new javax.swing.JFormattedTextField(createFormatter("####"));
        jLabel6 = new javax.swing.JLabel();
        txtNombreBD = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(adsec.presentacion.LiceoEscazuApp.class).getContext().getResourceMap(LoginDialog.class);
        lbFotoLiceo.setIcon(resourceMap.getIcon("lbFotoLiceo.icon")); // NOI18N
        lbFotoLiceo.setName("lbFotoLiceo"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        txtFechaHora.setEditable(false);
        txtFechaHora.setName("txtFechaHora"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(adsec.presentacion.LiceoEscazuApp.class).getContext().getActionMap(LoginDialog.class, this);
        btnAvanzado.setAction(actionMap.get("switchAvanzado")); // NOI18N
        btnAvanzado.setText(resourceMap.getString("btnAvanzado.text")); // NOI18N
        btnAvanzado.setName("btnAvanzado"); // NOI18N

        btnIngresar.setAction(actionMap.get("accionIngresar")); // NOI18N
        btnIngresar.setText(resourceMap.getString("btnIngresar.text")); // NOI18N
        btnIngresar.setName("btnIngresar"); // NOI18N
        btnIngresar.setSelected(true);

        lbUsuario.setText(resourceMap.getString("lbUsuario.text")); // NOI18N
        lbUsuario.setName("lbUsuario"); // NOI18N

        lbPassword.setText(resourceMap.getString("lbPassword.text")); // NOI18N
        lbPassword.setName("lbPassword"); // NOI18N

        txtUsuario.setName("txtUsuario"); // NOI18N

        txtPassword.setName("txtPassword"); // NOI18N

        btnCancelar.setAction(actionMap.get("accionCancelar")); // NOI18N
        btnCancelar.setText(resourceMap.getString("btnCancelar.text")); // NOI18N
        btnCancelar.setName("btnCancelar"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        txtDirServidor.setText(resourceMap.getString("txtDirServidor.text")); // NOI18N
        txtDirServidor.setName("txtDirServidor"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        txtUsuarioBD.setText(resourceMap.getString("txtUsuarioBD.text")); // NOI18N
        txtUsuarioBD.setName("txtUsuarioBD"); // NOI18N

        txtPasswordBD.setText(resourceMap.getString("txtPasswordBD.text")); // NOI18N
        txtPasswordBD.setName("txtPasswordBD"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        chbGuardarPassword.setSelected(true);
        chbGuardarPassword.setText(resourceMap.getString("chbGuardarPassword.text")); // NOI18N
        chbGuardarPassword.setName("chbGuardarPassword"); // NOI18N

        btnProbarConexion.setAction(actionMap.get("probarConexion")); // NOI18N
        btnProbarConexion.setText(resourceMap.getString("btnProbarConexion.text")); // NOI18N
        btnProbarConexion.setName("btnProbarConexion"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        txtPuerto.setText(resourceMap.getString("txtPuerto.text")); // NOI18N
        txtPuerto.setName("txtPuerto"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        txtNombreBD.setText(resourceMap.getString("txtNombreBD.text")); // NOI18N
        txtNombreBD.setName("txtNombreBD"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbFotoLiceo)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtFechaHora, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lbUsuario)
                            .addComponent(lbPassword))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(chbGuardarPassword)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnAvanzado)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 218, Short.MAX_VALUE)
                                .addComponent(btnIngresar))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(30, 30, 30)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel5)
                                            .addComponent(jLabel2)))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel3)
                                        .addComponent(jLabel4)
                                        .addComponent(jLabel6)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtNombreBD, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                                    .addComponent(txtUsuarioBD, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                                    .addComponent(txtPuerto, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                                    .addComponent(txtDirServidor, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                                    .addComponent(txtPasswordBD, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar))
                    .addComponent(btnProbarConexion, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbFotoLiceo)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtFechaHora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbUsuario))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbPassword))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chbGuardarPassword)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnIngresar)
                    .addComponent(btnAvanzado))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtDirServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtUsuarioBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPasswordBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtNombreBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnProbarConexion)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        Date tiempo = new Date(System.currentTimeMillis());
        txtFechaHora.setText(UtilidadesCapaNegocios.obtenerStringFechaHora(tiempo));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                LoginDialog dialog = new LoginDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    @Action
    public void switchAvanzado() {
        if(this.btnAvanzado.isSelected()){
            this.btnAvanzado.setText("<< Avanzado");
            this.setSize(this.tamañoPanelGrande);
        }else{
            this.btnAvanzado.setText("Avanzado >>");
            this.setSize(this.tamañoPanelPequeño);
        }
    }//fin de switchAvanzado

    @Action
    public void accionIngresar() {
        String password = new String(this.txtPassword.getPassword());
        
        int resultado = this.controladoraLogin.ingresarUsuario(this.txtUsuario.getText(),
                password, this.txtDirServidor.getText(), this.txtPuerto.getText(),
                this.txtUsuarioBD.getText(), new String(this.txtPasswordBD.getPassword()),
				this.txtNombreBD.getText());

        switch(resultado){
            case ControladoraUsuario.NO_EXISTE_USUARIO:
                JOptionPane.showMessageDialog(this, "No existe el usuario", "ERROR", JOptionPane.ERROR_MESSAGE);
                break;
            case ControladoraUsuario.PASSWORD_MAL:
                JOptionPane.showMessageDialog(this, "La contraseña ingresada no corresponde al usuario", "ERROR", JOptionPane.ERROR_MESSAGE);
                break;
            case ControladoraUsuario.PASSWORD_OK_LOGIN_ERROR:
                JOptionPane.showMessageDialog(this, "Ha ocurrido un error al iniciar la sesión", "ERROR", JOptionPane.ERROR_MESSAGE);
                break;
            case ControladoraUsuario.PASSWORD_OK_LOGIN_OK:
                this.dispose();
                break;
            default:
                JOptionPane.showMessageDialog(this, "Ha ocurrido un error inesperado", "ERROR", JOptionPane.ERROR_MESSAGE);
                break;
        }//fin de switch

        if(!this.chbGuardarPassword.isSelected()){
            password = "";
        }
        this.controladoraLogin.guardarDatosConexion(this.txtUsuario.getText(), password,
                this.txtDirServidor.getText(), this.txtPuerto.getText(),
                this.txtUsuarioBD.getText(), new String(this.txtPasswordBD.getPassword()),
                this.txtNombreBD.getText(), this.chbGuardarPassword.isSelected());
    }//fin de accionIngresar

    @Action
    public void accionCancelar() {
        this.dispose();
    }//fin de accionCancelar
    

    @Action
    public void probarConexion() {
        AdministradorConexion adminConexion = AdministradorConexion.getInstancia();
        adminConexion.setUrlBD(this.txtDirServidor.getText(), this.txtPuerto.getText(), this.txtNombreBD.getText());
        adminConexion.setUsuario(this.txtUsuarioBD.getText());
        adminConexion.setPassword(new String(this.txtPasswordBD.getPassword()));
        Connection conexion = adminConexion.getConexion();
        if( conexion != null ){
            JOptionPane.showMessageDialog(this, "Conexión exitosa");
            adminConexion.cerrarConexion();
        }else{
            JOptionPane.showMessageDialog(this, "Conexión fallida");
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton btnAvanzado;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnIngresar;
    private javax.swing.JButton btnProbarConexion;
    private javax.swing.JCheckBox chbGuardarPassword;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel lbFotoLiceo;
    private javax.swing.JLabel lbPassword;
    private javax.swing.JLabel lbUsuario;
    private javax.swing.JTextField txtDirServidor;
    private javax.swing.JTextField txtFechaHora;
    private javax.swing.JTextField txtNombreBD;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JPasswordField txtPasswordBD;
    private javax.swing.JFormattedTextField txtPuerto;
    private javax.swing.JTextField txtUsuario;
    private javax.swing.JTextField txtUsuarioBD;
    // End of variables declaration//GEN-END:variables

}
